﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using NHibernate;
using Core.Infra.Factories;

namespace Core.Infra.Web {
    public class NHibernateSessionModule : IHttpModule {
        public static readonly string KEY = "NHibernateSession";
        private static ISession _session;

        public void Dispose() {
        }

        public void Init(HttpApplication context) {

            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        private void context_EndRequest(object sender, EventArgs e) {

            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;

            ISession session = context.Items[KEY] as ISession;
            if (session != null) {
                try {
                    session.Flush();
                    session.Close();
                } catch { }
            }
            context.Items[KEY] = null;
        }

        //Nao implementei
        private bool IsAjaxError() {
            return HttpContext.Current.Response.StatusCode == 500 && HttpContext.Current.Request.RawUrl.Contains(".asmx");
        }


        public static ISession OpenSession() {
            return SessionFactory.Create().OpenSession();
        }

        public static ISession CurrentSession {
            get {
                if (HttpContext.Current == null) {
                    if (_session != null) {
                        return _session;
                    } else {
                        _session = OpenSession();
                        return _session;
                    }
                } else {
                    HttpContext currentContext = HttpContext.Current;
                    ISession session = currentContext.Items[KEY] as ISession;
                    if (session == null) {
                        session = OpenSession();
                        currentContext.Items[KEY] = session;
                    }
                    return session;
                }
            }
        }

        private void context_BeginRequest(object sender, EventArgs e) {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            context.Items[KEY] = OpenSession();
        }
    }
}
